<template>
  <div class="publish">
    <van-nav-bar
      style="color: #fff"
      title="发布"
      @click-left="$router.back()"
      left-arrow
    />
    <div class="container">
      <van-form validate-first @failed="onFailed">
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
          style="margin-top: 10px"
          v-model="title"
          name="pattern"
          placeholder="请输入标题"
          :rules="[{ pattern: '', message: '至少6个字符' }]"
        />

        <van-field
          readonly
          clickable
          name="picker"
          v-model="value"
          placeholder="请选择"
          @click="showPicker = true"
        />
        <van-popup v-model="showPicker" position="bottom"
          ><van-picker
            show-toolbar
            :columns="columns"
            @confirm="onConfirm"
            @cancel="showPicker = false"
        /></van-popup>

        <van-field
          style="margin-top: 10px"
          v-model="content"
          rows="5"
          autosize
          type="textarea"
          :rules="[{ pattern: /[\w\W]{20,}/, message: '至少20个字符' }]"
          placeholder="请输入内容"
          show-word-limit
        />
        <van-field name="uploader" style="margin-top: 10px">
          <template #input>
            <van-uploader v-model="fileList" multiple :max-count="3" />
          </template>
        </van-field>

        <div style="margin: 30px 50px">
          <van-button
            round
            block
            type="primary"
            size="normal"
            :square="true"
            native-type="submit"
            @click="issue"
            >提交</van-button
          >
        </div>
      </van-form>
    </div>
    <van-tabbar v-model="active2">
      <van-tabbar-item icon="home-o" to="/">首页</van-tabbar-item>
      <van-tabbar-item
        icon="add-o"
        :to="{
          path: '/publish',
        }"
        >发布</van-tabbar-item
      >
      <van-tabbar-item icon="friends-o" to="/my">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active2: "",
      publishList: [],
      title: "",
      cate_id: "",
      content: "",
      fileList: [],
      author_id: "",
      value: "",
      ids: "",
      columns: [],
      showPicker: false,
    };
  },
  created() {
    this.publish();
    this.author_id = localStorage.getItem("uid");
    console.log(this.author_id);
  },
  methods: {
    onFailed(errorInfo) {
      console.log("failed", errorInfo);
    },
    onConfirm(value, index) {
      this.value = value;
      this.showPicker = false;
      this.ids = this.publishList[index]._id;
      console.log(this.ids);
    },
    async publish() {
      const { data: res } = await this.axios({
        method: "POST",
        url: "/api/get_cate_list",
      });
      if (res.code == 0) {
        this.publishList = res.data;
        console.log(this.publishList);
        // console.log(this.publishList);

        // 循环遍历出名字
        const arr = [];
        this.publishList.forEach((v) => {
          arr.push(v.name);
        });
        console.log(arr);
        this.columns = arr;
      }
    },
    // 上传图片
    async upload(fileList) {
      // 1.判断一下选图片了没
      let imageSrc = [];
      if (!fileList || fileList.length == 0) {
        return imageSrc;
      }
      // 多个异步任务都执行完成 返回他们完成后的结过
      let task = fileList.map((v) => {
        return new Promise(async (resolve, reject) => {
          let { file } = v;

          let { type } = file;

          //  拿到类型  比如jpg
          type = type.split("/")[1];
          // 重新命名  随机名字
          let file_name = `${new Date().getTime()}_${Math.random()
            .toString(36)
            .slice(2)}.${type}`;

          // 去服务器申请一个上传token

          let {
            data: { token },
          } = await this.axios.get("/upload/token");
          console.log(token);
          const formdata = new FormData();
          formdata.append("file", file);
          formdata.append("token", token);
          formdata.append("key", file_name);

          // 向七牛云请求
          this.axios
            .post("https://upload-z1.qiniup.com", formdata)
            .then((res) => {
              console.log(res);
              resolve(`http://toutiao.longxiaokj.com/` + res.data.key);
            });
        });
      });
      imageSrc = await Promise.all(task);
      console.log(imageSrc);
      return imageSrc;
    },
    async issue(values) {
      let { fileList, title, content, value, ids, author_id } = this;
      if (!this.author_id) {
        this.$toast("请先登录");
        setTimeout((v) => {
          this.$router.push("/");
        }, 500);
        return;
      }

      let imageSrc = await this.upload(fileList);
      console.log(imageSrc);
      const { data: res } = await this.axios.post("/api/add_article", {
        title: this.title,
        content: this.content,
        cate_name: this.value,
        cate_id: this.ids,
        author: "1",
        author_id: this.author_id,
        imageSrc,
      });
      console.log(res);
      if (res.code == 0) {
        this.$toast("发布成功");
        setTimeout((v) => {
          this.$router.push("/login");
        }, 500);
      }
      delete values.fileList;
    },
  },
};
</script>
<style lang="scss">
.van-nav-bar {
  background-color: #07c160;
}
</style>
